﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media.Media3D;
using static System.Net.Mime.MediaTypeNames;

namespace SuperKit {
    class BindSrt : MediaExecutor {
        // 指定类型的扩展名
        public string Ext { get;  }
        // 指定字幕的扩展名
        public string Sub { get; }

        public BindSrt(ArgReader arg, IExecutorOwner form, string fpath) : base(arg, form, fpath) {
            Ext = arg.GetParameter("-ext", "mp4");
            Sub = arg.GetParameter("-sub", "srt");
        }

        public override void Execute() {
            Thread t = new Thread(OnProcess);
            t.Start();
        }

        private void OnProcess() {
            var files = new List<FileInfo>();
            var dir = new DirectoryInfo(FilePath);
            GetAllFiles(dir, files, null);
            var targetPath = CreateTargetDir(true);

            foreach (var file in files) {
                // 得到去掉点号的扩展名
                var ext = Path.GetExtension(file.Name).Replace(".", "");
                if (Kit.IsEqual(ext, Ext) == false) {
                    continue;
                }

                // 得到新文件的Path
                var newPath = FileCollector.CalculateNewPath(dir.FullName, targetPath, file.FullName);
                // 检查目录
                EstablishDirectory(newPath);

                // 查找相同名称的字幕
                FileInfo sub = FindSubFile(file, files);
                // 如果没有找到，提示错误
                if (sub == null) {
                    Flush("文件 {0} 没有对应的字幕文件！将直接复制！", file.Name);
                    File.Copy(file.FullName, newPath, true);
                    continue; 
                }


                string cmd = string.Format("-i \"{0}\" -i \"{1}\" -c:s mov_text -c:v copy -c:a copy \"{2}\"",
                    file.FullName, sub.FullName, newPath);

                Flush("Move To:{0}", newPath);

                ExecuteFFMpeg(cmd);
            }


            End();
        }

        private FileInfo FindSubFile(FileInfo file, List<FileInfo> files) {
            // 得到纯文件名
            var pureName = Path.GetFileNameWithoutExtension(file.Name);
            // 得到字幕
            var subName = string.Format("{0}.{1}", pureName, Sub);

            // 查找
            foreach (FileInfo i in files) {
                if (Kit.IsEqual(i.Name, subName)) {
                    return i;
                }
            }

            return null;
        }

        private void ProcessDir(DirectoryInfo dir) {


            var files = dir.GetFiles();

            foreach (var i in files) {

            }
        }

    }
}
